/*
 * Copyright(c) 2023 NeatLogic Co., Ltd. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package neatlogic.framework.notify.core;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import neatlogic.framework.asynchronization.threadpool.CachedThreadPool;
import neatlogic.framework.notify.dto.NotifyVo;
import neatlogic.module.framework.notify.exception.ExceptionNotifyThread;
import neatlogic.module.framework.notify.exception.ExceptionNotifyTriggerType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class NotifyHandlerBase implements INotifyHandler {

    private static final Logger logger = LoggerFactory.getLogger(NotifyHandlerBase.class);

    public final boolean execute(NotifyVo notifyVo) throws Exception {

        if (StringUtils.isNotBlank(notifyVo.getError())) {
            logger.error(notifyVo.getError());
            if (notifyVo.getIsSendExceptionNotify() == 1) {
                notifyVo.setIsSendExceptionNotify(0);// 防止循环调用NotifyPolicyUtil.execute方法
                notifyVo.appendError("<br>data：<xmp>");
                notifyVo.appendError(JSONObject.toJSONString(notifyVo.getData(), SerializerFeature.PrettyFormat));
                notifyVo.appendError("</xmp><br>titleTemplate：<xmp>");
                notifyVo.appendError(notifyVo.getTemplateTitle());
                notifyVo.appendError("</xmp><br>contentTemplate：<xmp>");
                notifyVo.appendError(notifyVo.getTemplateContent());
                notifyVo.appendError("</xmp><br>");
                CachedThreadPool.execute(new ExceptionNotifyThread(notifyVo, ExceptionNotifyTriggerType.EMAILNOTIFYEXCEPTION));
            }
            return false;
        } else {
            return myExecute(notifyVo);
        }

    }

    protected abstract boolean myExecute(NotifyVo notifyVo) throws Exception;
}
